package com.bw.good

import android.content.Intent
import android.view.View
import androidx.activity.viewModels
import androidx.recyclerview.widget.GridLayoutManager
import com.alibaba.android.arouter.launcher.ARouter
import com.bawei.base.RoutePath
import com.bawei.common.mvi.BaseMviActivity
import com.bawei.good.R
import com.bawei.good.databinding.ActivityZfactivityBinding
import com.bw.good.adapter.GoodListAdapter
import com.bw.good.adapter.GoodLiveAdapter
import com.bw.good.entity.GoodEntity
import com.bw.good.intent.GoodViewIntent
import com.bw.good.state.GoodUiState
import com.bw.good.vm.GoodViewModel
import dagger.hilt.android.AndroidEntryPoint

@AndroidEntryPoint
class ZFActivity : BaseMviActivity<ActivityZfactivityBinding>() {

    private val mViewModel: GoodViewModel by viewModels()

    private lateinit var mAdapter: GoodLiveAdapter

    private val list =  mutableListOf<GoodEntity>()

    private var categoryId: Int = 0
    private var currentPage: Int = 1
    private var pageSize: Int = 20

    override fun getLayoutId(): Int = R.layout.activity_zfactivity

    override fun initViews() {
        mAdapter = GoodLiveAdapter(list)
        mDataBinding.rvGoodList.apply {
            layoutManager = GridLayoutManager(this@ZFActivity,2)
            adapter = mAdapter
        }

        //点击返回首页
        mDataBinding.tvBack.setOnClickListener {
            this@ZFActivity.finish()
        }

        //点击跳转到订单页面
        mDataBinding.tvDingdan.setOnClickListener {
            ARouter.getInstance().build(RoutePath.PATH_MINE_PAGE).navigation()
            this@ZFActivity.finish()
        }

        //点击跳转到详情页面
        mAdapter.setItemClickListener(object : GoodLiveAdapter.GoodItemClickListener{
            override fun onItemClickChildClick(v: View, position: Int, entity: GoodEntity) {
                if (v.id == R.id.iv_good_icon) {
                    ARouter.getInstance().build(RoutePath.PATH_GOOD_DETAIL_PAGE).withSerializable("entity", list[position]).navigation()
                }
            }
        })
    }

    override suspend fun sendViewIntent() {
        mViewModel.channel.send(GoodViewIntent.LoadGoodList(categoryId, currentPage, pageSize))
    }

    override suspend fun collectUiState() {
        mViewModel.uiState.collect {
            when(it) {
                is GoodUiState.LoadGoodListSuccess -> {
                    list.clear()
                    list.addAll(it.list)
                    mAdapter.notifyDataSetChanged()
                }
                is GoodUiState.LoadGoodListFail -> {
                    showToastMsg("请求失败")
                }
                else -> {}
            }
        }
    }

}